
package com.wyzz.hr.base;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.wyzz.hr.bo.AuthorityPosBo;
import com.wyzz.hr.bo.IAttdMachineBO;
import com.wyzz.hr.bo.IAttendmonthlyBO;
import com.wyzz.hr.bo.IBenefitTypeBO;
import com.wyzz.hr.bo.ICompaplanBo;
import com.wyzz.hr.bo.IContractTypeBo;
import com.wyzz.hr.bo.IDepartmentBO;
import com.wyzz.hr.bo.IEcptypeBO;
import com.wyzz.hr.bo.IEmpAddConfBo;
import com.wyzz.hr.bo.IEmpBenefitPlanBo;
import com.wyzz.hr.bo.IEmpSalaryAcctBo;
import com.wyzz.hr.bo.IEmpTypeBO;
import com.wyzz.hr.bo.IEmployeeBo;
import com.wyzz.hr.bo.IEmpsalaryperiodBo;
import com.wyzz.hr.bo.IHasAuthBO;
import com.wyzz.hr.bo.IJobTitleBo;
import com.wyzz.hr.bo.IJobgradeBO;
import com.wyzz.hr.bo.ILeavetypeBO;
import com.wyzz.hr.bo.ILocationBO;
import com.wyzz.hr.bo.IOrgheadsBo;
import com.wyzz.hr.bo.IOvertimetypeBo;
import com.wyzz.hr.bo.IPositionBaseBo;
import com.wyzz.hr.bo.ISalaryconfBo;
import com.wyzz.hr.pojo.Department;
import com.wyzz.hr.pojo.Employee;
import com.wyzz.hr.pojo.Location;
import com.wyzz.hr.pojo.Userinfo;
import com.wyzz.hr.spring.SpringBeanFactory;
import com.wyzz.hr.util.BaseCrit;
import com.wyzz.hr.util.Interpreter;
import com.wyzz.hr.util.InterpreterException;
import com.wyzz.hr.util.ObjectUtil;
import com.wyzz.hr.util.Pager;
import com.wyzz.hr.util.StringUtil;

import java.io.PrintStream;
import java.util.*;
import javax.servlet.http.*;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;


public class BaseAction extends ActionSupport implements Constants, Preparable {

	public BaseAction() {
		authorityCondition = null;
	}

	protected HttpServletRequest getRequest() {
		if (ServletActionContext.getRequest() != null)
			return ServletActionContext.getRequest();
		else
			return WebContextFactory.get().getHttpServletRequest();
	}

	protected HttpServletResponse getResponse() {
		if (ServletActionContext.getResponse() != null)
			return ServletActionContext.getResponse();
		else
			return WebContextFactory.get().getHttpServletResponse();
	}

	protected HttpSession getSession() {
		return getRequest().getSession();
	}

	public static Object getBean(String beanName) {
		try {
			return SpringBeanFactory.getBean(beanName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public void addSuccessInfo(String info) {
		addFieldError("success", info);
	}

	public void addSuccessInfo(String info, Object variables[]) {
		String errContent = StringUtil.messageNoErrCode(info, variables);
		addFieldError("success", errContent);
	}

	public void addErrorInfo(String err) {
		addFieldError("error", err);
	}

	public void addErrorInfo(String err, Object variables[]) {
		String errContent = StringUtil.messageNoErrCode(err, variables);
		addFieldError("error", errContent);
	}

	public void addActionErrorInfo(String err, Object variables[]) {
		String errContent = StringUtil.messageNoErrCode(err, variables);
		addActionError(errContent);
	}

	public void addSuccessInfo(List info) {
		if (info == null)
			return;
		for (Iterator iter = info.iterator(); iter.hasNext(); addFieldError(
				"success", iter.next().toString()))
			;
	}

	public void addErrorInfo(List err) {
		if (err == null)
			return;
		for (Iterator iter = err.iterator(); iter.hasNext(); addFieldError(
				"error", iter.next().toString()))
			;
	}

	public void addDwrInfo(String errMsg) {
		int index = errMsg.indexOf(":");
		if (index == -1 || index > 16) {
			addFieldError("error", errMsg);
			return;
		}
		if (errMsg.indexOf("SUCC:") != -1)
			addFieldError("success", errMsg.substring(index + 1));
		else
			addFieldError("error", errMsg.substring(index + 1));
	}

	public boolean addSubDC(DetachedCriteria dc, String alias, int module) {
		AuthorityPosBo authposBo = (AuthorityPosBo) getBean("authPosService");
		String deptLocsInCharge[][] = authposBo.getDeptAndLocInCharge(
				getCurrentPosNo(), Integer.valueOf(module));
		if (deptLocsInCharge == null) {
			if (!StringUtils.isEmpty(alias))
				alias = (new StringBuilder()).append(alias).append(".")
						.toString();
			BaseCrit.addDC(dc, (new StringBuilder()).append(alias).append(
					Employee.PROP_ID).toString(), "eq",
					new String[] { getCurrentEmpNo() });
			return false;
		} else {
			String deptsInCharge[] = deptLocsInCharge[0];
			String locsInCharge[] = deptLocsInCharge[1];
			BaseCrit.addOrgDC(dc, alias, deptsInCharge, locsInCharge);
			return true;
		}
	}

	public boolean checkEmpInCharge(Employee subEmp, int module) {
		AuthorityPosBo authposBo = (AuthorityPosBo) getBean("authPosService");
		String deptLocsInCharge[][] = authposBo.getDeptAndLocInCharge(
				getCurrentPosNo(), Integer.valueOf(module));
		if (deptLocsInCharge == null)
			return false;
		if (ObjectUtil.contains(deptLocsInCharge[0], subEmp.getEmpDeptNo()
				.getId()))
			return true;
		return ObjectUtil.contains(deptLocsInCharge[1], subEmp
				.getEmpLocationNo().getId());
	}

	public static void addOrders(DetachedCriteria dc, Pager page,
			String defaultOrders[]) {
		if (page != null && StringUtils.isNotEmpty(page.getOrder())
				&& page.getOrder().indexOf("-") > 0) {
			String param[] = page.getOrder().split("-");
			if (param.length > 1)
				if ("up".equals(param[1]))
					dc.addOrder(Order.asc(param[0]));
				else
					dc.addOrder(Order.desc(param[0]));
		}
		if (defaultOrders != null && defaultOrders.length > 0) {
			String arr$[] = defaultOrders;
			int len$ = arr$.length;
			for (int i$ = 0; i$ < len$; i$++) {
				String orders = arr$[i$];
				if (orders == null)
					continue;
				String param[] = orders.split("-");
				if (param.length <= 1)
					continue;
				if ("up".equals(param[1]))
					dc.addOrder(Order.asc(param[0]));
				else
					dc.addOrder(Order.desc(param[0]));
			}

		}
	}

	public static List getDrillDown(String className, String variables[]) {
		className = className.toLowerCase();
		if ("attdmachine".equals(className)) {
			IAttdMachineBO attdMachineBO = (IAttdMachineBO) SpringBeanFactory
					.getBean("attdMachineBO");
			if (variables == null || variables.length == 0
					|| "0".equals(variables[0]))
				return attdMachineBO.FindEnabledAttdMachine();
			else
				return attdMachineBO.FindAllAttdMachine();
		}
		if ("benefittype".equals(className)) {
			IBenefitTypeBO benefitTypeBo = (IBenefitTypeBO) SpringBeanFactory
					.getBean("benefitTypeBo");
			return benefitTypeBo.findAll();
		}
		if ("compaplanstatus".equals(className)) {
			ICompaplanBo compaplanBo = (ICompaplanBo) getBean("compaplanBo");
			return compaplanBo.getCompStatus();
		}
		if ("contracttype".equals(className)) {
			IContractTypeBo contTypeBo = (IContractTypeBo) getBean("contractTypeBo");
			return contTypeBo.FindAllEcptype();
		}
		if ("costcenter".equals(className)) {
			ISalaryconfBo salaryConfBo = (ISalaryconfBo) getBean("salaryconfBo");
			return salaryConfBo.getAllCostCenter();
		}
		if ("department".equals(className)) {
			IDepartmentBO deptbo = (IDepartmentBO) getBean("departmentBO");
			if (variables == null || variables.length == 0
					|| "0".equals(variables[0]))
				return deptbo.FindEnabledDepartment();
			else
				return deptbo.FindAllDepartment();
		}
		if ("ebpyear".equals(className)) {
			IEmpBenefitPlanBo ebpBo = (IEmpBenefitPlanBo) getBean("empbenefitplanBo");
			return ebpBo.getAllYears();
		}
		if ("ecptype".equals(className)) {
			IEcptypeBO ecpbo = (IEcptypeBO) SpringBeanFactory
					.getBean("ecptypeBO");
			return ecpbo.FindAllEcptype();
		}
		if ("empaddconf".equals(className)) {
			IEmpAddConfBo empAddConfBo = (IEmpAddConfBo) getBean("empAddConfBo");
			if (variables == null || variables.length == 0)
				return empAddConfBo.listByTable("empAdditional");
			else
				return empAddConfBo.listByTable(variables[0]);
		}
		if ("empsalaryacct".equals(className)) {
			IEmpSalaryAcctBo esaBo = (IEmpSalaryAcctBo) getBean("empsalaryacctBo");
			return esaBo.searchAllEmpsalaryacctVersionInUse();
		}
		if ("empsalaryperiod".equals(className)) {
			IEmpsalaryperiodBo salaryperiod = (IEmpsalaryperiodBo) getBean("empsalaryperiodBO");
			return salaryperiod.getAllYears();
		}
		if ("empstatus".equals(className)) {
			IEmployeeBo empBo = (IEmployeeBo) getBean("empBo");
			return empBo.getEmpStatus();
		}
		if ("emptype".equals(className)) {
			IEmpTypeBO emptypebo = (IEmpTypeBO) SpringBeanFactory
					.getBean("emptypeBO");
			if (variables == null || variables.length == 0
					|| "0".equals(variables[0]))
				return emptypebo.FindEnabledEmpType();
			else
				return emptypebo.FindAllEmpType();
		}
		if ("jobgrade".equals(className)) {
			IJobgradeBO gradeBo = (IJobgradeBO) SpringBeanFactory
					.getBean("jobgradeBO");
			return gradeBo.FindAllJobgrade();
		}
		if ("jobtitle".equals(className)) {
			IJobTitleBo jobTitleBo = (IJobTitleBo) getBean("jobTitleBo");
			if (variables == null || variables.length == 0
					|| "0".equals(variables[0]))
				return jobTitleBo.FindEnabledJobTitle();
			else
				return jobTitleBo.FindAllJobTitle();
		}
		if ("leavetype".equals(className)) {
			ILeavetypeBO lt_BO = (ILeavetypeBO) getBean("leavetypeBO");
			return lt_BO.FindAllLeaveType();
		}
		if ("location".equals(className)) {
			ILocationBO localbo = (ILocationBO) SpringBeanFactory
					.getBean("locationBO");
			if (variables == null || variables.length == 0
					|| "0".equals(variables[0]))
				return localbo.FindEnabledLocation();
			else
				return localbo.FindAllLocation();
		}
		if ("overtimetype".equals(className)) {
			IOvertimetypeBo ot_BO = (IOvertimetypeBo) getBean("overtimetypeBO");
			return ot_BO.FindAllOtType();
		}
		if ("positionbase".equals(className)) {
			IPositionBaseBo pbBo = (IPositionBaseBo) SpringBeanFactory
					.getBean("positionBaseBo");
			if (variables == null || variables.length == 0
					|| "0".equals(variables[0]))
				return pbBo.findAllActivePb();
			else
				return pbBo.findAllPbs();
		}
		if ("attendperiod".equals(className)) {
			IAttendmonthlyBO attendmothlyBO = (IAttendmonthlyBO) SpringBeanFactory
					.getBean("attendmonthlyBo");
			return attendmothlyBO.getAllYears();
		} else {
			return null;
		}
	}

	/**
	 * @deprecated Method checkOrgInCharge is deprecated
	 */

	public static boolean checkOrgInCharge(Employee emp, String orgId) {
		if (emp == null || orgId == null || orgId.trim().equals("")) {
			return false;
		} else {
			IOrgheadsBo headsBo = (IOrgheadsBo) getBean("headsBo");
			String hql = (new StringBuilder()).append(
					"from Orgheads where orgheadsOrgNo='").append(orgId)
					.append("' and orgheadsEmpNo='").append(emp.getId())
					.append("'").toString();
			return headsBo.exeHqlList(hql).size() > 0;
		}
	}

	/**
	 * @deprecated Method checkDeptInCharge is deprecated
	 */

	public static boolean checkDeptInCharge(Employee emp, Department dept) {
		if (emp == null || dept == null || emp.getId() == null
				|| dept.getId() == null)
			return false;
		else
			return checkOrgInCharge(emp, dept.getId());
	}

	/**
	 * @deprecated Method checkAreaInCharge is deprecated
	 */

	public static boolean checkAreaInCharge(Employee emp, Location location) {
		if (emp == null || location == null || emp.getId() == null
				|| location.getId() == null)
			return false;
		else
			return checkOrgInCharge(emp, location.getId());
	}

	/**
	 * @deprecated Method checkAreaInCharge is deprecated
	 */

	public static boolean checkAreaInCharge(Employee employer, Employee employee) {
		if (employer == null || employee == null)
			return false;
		try {
			IEmployeeBo employeeBo = (IEmployeeBo) getBean("empBo");
			employee = employeeBo.loadEmp(employee.getId(), null);
			IOrgheadsBo headsBo = (IOrgheadsBo) getBean("headsBo");
			String hql = (new StringBuilder()).append(
					"from Orgheads where orgheadsOrgNo='").append(
					employee.getEmpLocationNo().getId()).append(
					"' and orgheadsEmpNo='").append(employer.getId()).append(
					"'").toString();
			return headsBo.exeHqlList(hql).size() > 0;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * @deprecated Method checkDeptInCharge is deprecated
	 */

	public static boolean checkDeptInCharge(Employee emp, Employee employee) {
		if (emp == null || employee == null)
			return false;
		IEmployeeBo empBo = (IEmployeeBo) getBean("empBo");
		employee = empBo.loadEmp(employee.getId(),
				new String[] { Employee.PROP_EMP_DEPT_NO });
		Department dept = employee.getEmpDeptNo();
		if (dept == null || dept.getDepartmentHead() == null
				&& dept.getDepartmentOtherHeads() == null)
			return false;
		String head = dept.getDepartmentHead();
		String otherHeads = dept.getDepartmentOtherHeads();
		if (head != null && head.equals(emp.getId()))
			return true;
		return otherHeads != null && otherHeads.indexOf(emp.getId()) != -1;
	}

	/**
	 * @deprecated Method hasHeader is deprecated
	 */

	public static boolean hasHeader(String orgId) {
		if (orgId == null) {
			return false;
		} else {
			IOrgheadsBo headsBo = (IOrgheadsBo) getBean("headsBo");
			String hql = (new StringBuilder()).append(
					"from Orgheads where orgheadsOrgNo='").append(orgId)
					.append("'").toString();
			return headsBo.exeHqlList(hql).size() > 0;
		}
	}

	public boolean hasAuth(int moduleId, int condition[]) {
		IHasAuthBO bo = (IHasAuthBO) SpringBeanFactory.getBean("hasService");
		UsersAuthority userAuthority;
		if (condition != null && condition.length > 0)
			userAuthority = new UsersAuthority(String.valueOf(moduleId),
					new String[] { String.valueOf(condition[0]) });
		else
			userAuthority = new UsersAuthority(String.valueOf(moduleId),
					new String[0]);
		try {
			return bo.hasActionAuth(userAuthority);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public boolean hasAuth(String moduleId, String condition[]) {
		IHasAuthBO bo = (IHasAuthBO) SpringBeanFactory.getBean("hasService");
		UsersAuthority userAuthority;
		if (condition != null && condition.length > 0)
			userAuthority = new UsersAuthority(moduleId,
					new String[] { condition[0] });
		else
			userAuthority = new UsersAuthority(moduleId, new String[0]);
		try {
			return bo.hasActionAuth(userAuthority);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public boolean hasAuths(String authString) {
		String authStr;
		authStr = authString.replaceAll(" ", "").toUpperCase();
		authStr = Interpreter.removeBrackets(authStr);
		if (StringUtils.isEmpty(authStr))
			return false;
		String splitAuthStr[];
		try {
			splitAuthStr = Interpreter.seperateauthString(authStr);
			if (splitAuthStr.length == 3) {
				boolean result = hasAuths(splitAuthStr[0]);
				boolean resultRight = hasAuths(splitAuthStr[1]);
				if ("AND".equals(splitAuthStr[2]))
					result = result && resultRight;
				else if ("OR".equals(splitAuthStr[2]))
					result = result || resultRight;
				else
					throw new InterpreterException((new StringBuilder())
							.append("\u903B\u8F91\u8FD0\u7B97\u7B26").append(  //逻辑运算符
									splitAuthStr[2]).append(
									"\u9519\u8BEF\uFF01").toString());  //错误
				return result;
			}
			if (splitAuthStr.length == 2) {
				boolean result = hasAuths(splitAuthStr[0]);
				if ("NOT".equals(splitAuthStr[1]))
					result = !result;
				else
					throw new InterpreterException((new StringBuilder())
							.append("\u903B\u8F91\u8FD0\u7B97\u7B26").append(
									splitAuthStr[1]).append(
									"\u9519\u8BEF\uFF01").toString());
				return result;
			}
		} catch (InterpreterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String authArray[];
		authArray = authStr.split(",");
		if (authArray == null || authArray.length == 0)
			try {
				throw new InterpreterException((new StringBuilder()).append(
						"\u5B57\u7B26\u4E32").append(authStr).append(  //字符串
						"\u53C2\u6570\u5F02\u5E38\uFF01").toString());  //参数异常！
			} catch (InterpreterException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		if (authArray.length == 1)
			return hasAuth(authArray[0], new String[0]);
		if (authArray.length == 2)
			return hasAuth(authArray[0], new String[] { authArray[1] });
		try {
			throw new InterpreterException((new StringBuilder()).append(
					"\u5B57\u7B26\u4E32").append(authStr).append(
					"\u53C2\u6570\u8FC7\u591A\uFF01").toString());  //参数过多
		} catch (InterpreterException ie) {
			System.out.println((new StringBuilder()).append(authStr).append(
					" \u6743\u9650\u516C\u5F0F\u89E3\u6790\u9519\u8BEF: ")  //权限公式解析错误:
					.append(ie.getMessage()).toString());
		}
		return false;
	}

	public boolean hasMultipleAuth(String authString) {
		if (authString == null)
			return false;
		IHasAuthBO hasAuthBO = (IHasAuthBO) SpringBeanFactory
				.getBean("hasService");
		String authArray[] = authString.split("#");
		List list = new ArrayList();
		String checkAuth = "";
		for (int i = 0; i < authArray.length; i++) {
			checkAuth = authArray[i];
			if (checkAuth.indexOf(",") == -1) {
				UsersAuthority userAuthority = new UsersAuthority(checkAuth,
						new String[0]);
				list.add(userAuthority);
			} else {
				UsersAuthority userAuthority = new UsersAuthority(checkAuth
						.substring(0, checkAuth.indexOf(",")),
						new String[] { checkAuth.substring(checkAuth
								.indexOf(",") + 1) });
				list.add(userAuthority);
			}
		}

		try {
			return hasAuthBO.hasActionAuth(list);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public String checkActionAuth(String actionName, String methodName) {
		IHasAuthBO bo;
		Iterator iterator;
		bo = (IHasAuthBO) SpringBeanFactory.getBean("hasService");
		List userAuthorityList = ActionAuths.getActionAuths(actionName,
				methodName);
		if (userAuthorityList == null || userAuthorityList.size() < 1)
			return null;
		iterator = userAuthorityList.iterator();
		while (iterator.hasNext()) {
			UsersAuthority userAuthority = (UsersAuthority) iterator.next();
			try {
				if (!bo.hasActionAuth(userAuthority))
					continue;
			} catch (Exception e) {
				e.printStackTrace();
				return "error";
			}
			String filter = userAuthority.getFilter();
			return filter;
		}
		return null;
	}

	public boolean checkAuth(String empId) {
		DetachedCriteria dc = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Employee.class);
		addSubDC(dc, "", 1);
		BaseCrit.addDC(dc, Employee.PROP_ID, "eq", new String[] { empId });
		IEmployeeBo empBo = (IEmployeeBo) getBean("empBo");
		List list = empBo.findByCriteria(dc);
		return list != null && !list.isEmpty();
	}

	public String getCurrentPosNo() {
		return (String) getSession().getAttribute("positionId");
	}

	public String getCurrentEmpNo() {
		return ((Userinfo) getSession().getAttribute("userinfo")).getId();
	}

	public Employee getCurrentEmp() {
		return ((Userinfo) getSession().getAttribute("userinfo")).getEmployee();
	}

	public void setAuthorityCondition(String authorityCondition) {
		this.authorityCondition = authorityCondition;
	}

	public void prepare() throws Exception {
	}

	private static final long serialVersionUID = 0x7627b229L;
	public static final String NOAUTH = "noauth";
	public static final String DOWNLOAD = "download";
	public static final String INVALID_TOKEN = "invalid.token";
	public static final String PARAM_SUCC = "param_succ";
	public static final String PARAMS_ERROR = "params_error";
	public static final String ChangeIodefPwd = "wyzzTagsAdmin";
	protected String authorityCondition;
}
